<?php
namespace App\Http\Controllers\Wap;

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsBuys;
use App\Models\GoodsEvaluate;
use App\Models\Location;
use App\Models\Member;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Services\ChuangLan\ChuanglanSmsApi;

/**
 * 推广
 *
 * @author Miluo Huang
 */
class SpreadController extends Controller
{
    public function __construct(Request $request)
    {
        if ($request->has('source')) {
            $channel = get_reserve_source($request->input('source'));
            \Session::put('channel', $channel);
        }
    }

    /**
     * 推广
     */
    public function getGoodDetail(Request $request)
    {
        //取得省市区数据
        if (Cache::has('wap_p_location') && Cache::get('wap_p_location')) {
            $province = Cache::get('wap_p_location');
        } else {
        $province = Location::where('pid', 0)->get();
            Cache::put('wap_p_location', $province, 200);
        }
        //取的商品数据
        if (Cache::has('wap_goods_info_' . $request->input('id'))) {
            $data = Cache::get('wap_goods_info_' . $request->input('id'));
        } else {
        $data = Goods::find($request->input('id'));
            Cache::put('wap_goods_info_' . $request->input('id'), $data, 15);
        }

        $attributes = [];
        foreach ($data->goods_attribute as $key => $item) {
            $attributes[] = explode('#', $item->value);
        }
        //获取产品
        $goods = Goods::where('status', 1)->orderBy('sort_at', 'desc')->where('status', 1)->where('is_item', 0)->get();
        //产品评价
        $eva = GoodsEvaluate::where('goods_id', $request->input('id'))->get();

        //购买记录
        $buys = GoodsBuys::where('goods_id', $request->input('id'))->get();

        // 替换图片
        $a = $data->details;
        $pregRule =  "/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img src="" style="max-width:100%" class="lazy" data-original="${1}'.'">', $a);
        $data->details = $content;

        return view('wap.spread.good')
            ->withProvince($province)
            ->withData($data)
            ->withAttributes($attributes)
            ->withGet($request->all())
            ->withGoods($goods)->withEva($eva)
            ->withHost($request->getHttpHost())
            ->withRand(rand(0, 99))
            ->withBuys($buys);
    }

    /**
     * 下单
     */
    public function orderSave(Request $request)
    {
        // 验证输入。
//        $this->validate($request, [
//            'size'        => 'required',
//            'color'       => 'required',
//            'number'      => 'required',
//            'real_name'   => 'required',
//            'mobile'      => [
//                'required',
//                'mobile'
//            ],
//            'province_id' => 'required',
//            'address'     => 'required',
//            'goods_id'    => 'required',
//            'city_id'     => 'required',
//            'area_id' => 'required'
//        ], [
//            'size.required'        => '请选择尺码',
//            'color.required'       => '请选择颜色',
//            'number.required'      => '请选择数量',
//            'real_name.required'   => '请填写姓名',
//            'mobile.required'      => '请填写手机号',
//            'mobile.mobile'        => '请填写正确手机号',
//            'province_id.required' => '请选择所在省份',
//            'address.required'     => '请填写详细地址',
//            'goods_id.required'    => '请选择商品',
//            'city_id.required'     => '请选择城市',
//            'area_id.required' => '请选择县市/地区'
//        ]);
        $post_addr = $request->input('post_addr');
        $spec_desc = $request->input('spec_desc');

        $member = Member::where('mobile', $request->input('post_tel'))->first();
        if (is_null($member)) {
            $member           = new Member();
            $member->mobile   = $request->input('post_tel');
            $member->nickname = $request->input('post_receiver');
            $member->save();
        }

        $count = Order::where('created_at', '>=', date('Y-m-d H:i:s', strtotime('-5 minute')))->where('member_id', $member->id)->count('id');
        if ($count >= 3) {
            return response()->json([
                'st'  => 0,
                'msg' => '购买太频繁,请稍后再试'
            ]);
        }

        $goods = Goods::find($request->input(
            'product_id'
        ));

        $order = new Order();
        $order->member()->associate($member);
        $order->address     = $post_addr['detail'];
        $order->province_id = $post_addr['province']['id'];
        $order->real_name   = $request->input('post_receiver');
        isset($post_addr['city']['id']) ? $order->city_id = $post_addr['city']['id'] : '';
        isset($post_addr['town']['id']) ? $order->area_id =  $post_addr['town']['id'] : '';
        $request->has('buyer_words') ? $order->leave_word = $request->input('buyer_words') : '';
        $request->has('product_id') ? $order->goods_id = $request->input('product_id') : '';
        $order->pay_mode = 1;
        $order->price    = $goods->present_price*$request->input('combo_num');
        if (\Session::has('channel')) {
            $order->channel()->associate(\Session::get('channel'));
        }
        $order->info = json_encode([
            '货品名' => $goods->name,
            '尺码'  => $spec_desc['0']['value'],
            '颜色'  => $request->input('combo_id'),
            '数量'  => $request->input('combo_num')
        ]);
        $order->save();
        $order->goods()->attach($request->input('product_id'));

        //发送短信
        $sms        = new ChuanglanSmsApi();
        $sms->sendSMS($request->input('post_tel'), $request->input('post_receiver').'女士您已成功订购'.$request->input('combo_num').'双' . $request->input('combo_id') .$spec_desc['0']['value'].'码鞋子，我们将尽快为您安排发货，请耐心等待。');
        return response()->json([
            'st'  => 1,
            'order_id' => $order->id,
            'msg' => '提交成功'
        ]);
    }

    /**
     * 首页
     */
    public function getHome(Request $request){
        $data = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',1)->get();
        $data2 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',2)->get();
        $data3 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',3)->get();
        $data4 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',4)->get();
        $data5 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',5)->get();
        $data7 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',7)->get();
        $top = Goods::where('top_recommended',1)->first();
        return view('wap.spread.index')->withData($data)->withHost($request->getHttpHost())->withTop($top)->withData2($data2)->withData3($data3)->withData4($data4)->withData5($data5)->withData7($data7);
    }

    /**
     * 订购成功
     */
    public function getResult(Request $request){
        $data = Order::find($request->input('order_id'));
        return view('wap.spread.result')->withData($data);
    }

}
